package com.huawei.codearts.tools.ratelimit.aspect;

import com.huawei.codearts.dao.RedisDao;
import com.huawei.codearts.tools.exception.ExceptionUtil;
import com.huawei.codearts.tools.ratelimit.annotation.LimitType;
import com.huawei.codearts.tools.ratelimit.annotation.RateLimiter;
import com.huawei.codearts.tools.utils.SecurityUtil;
import com.huawei.codearts.tools.utils.WebUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Map;


@Aspect
@Component
public class RateLimiterAspect {

    private static final Logger logger = LoggerFactory.getLogger(RateLimiterAspect.class);

    private final RedisDao redisDao;

    public RateLimiterAspect(RedisDao redisDao) {
        this.redisDao = redisDao;
    }

    @Before("@annotation(rateLimiter)")
    public void rateLimiter(JoinPoint joinPoint, RateLimiter rateLimiter) throws RuntimeException, UnknownHostException {
        int time = rateLimiter.time();
        int count = rateLimiter.count();
//        String key = getKey(joinPoint, LimitType.USER, rateLimiter.key(), rateLimiter.prefix());
//        System.out.println("key..."+key);
//        String combineKey = getCombineKey(rateLimiter, joinPoint);
        String combineKey = getKey(joinPoint, rateLimiter.limitType(), rateLimiter.key(), rateLimiter.prefix());
        Long number = redisDao.rateLimiter(combineKey, time, count);
        if (number == null || number.intValue() > count) {
            //超过限流阈值
            logger.info("当前接口以达到最大限流次数, key={}", combineKey);
            throw new RuntimeException("访问过于频繁，请稍后访问");
        }
        logger.info("一个时间窗内请求次数：{}，当前请求次数：{}，缓存的 key 为 {}", count, number, combineKey);
    }

    /**
     * 这个 key 其实就是接口调用次数缓存在 redis 的 key
     * rate_limit:11.11.11.11-com.huawei.codearts.controller.TestController-hello
     * rate_limit:com.huawei.codearts.controller.TestController-hello
     * @param rateLimiter
     * @param joinPoint
     * @return
     */
    private String getCombineKey(RateLimiter rateLimiter, JoinPoint joinPoint) {
        StringBuffer key = new StringBuffer(rateLimiter.key());
        if (rateLimiter.limitType() == LimitType.IP) {
            key.append(WebUtil.getIP()).append("-");
        }
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        key.append(method.getDeclaringClass().getName())
                .append("-")
                .append(method.getName());
        return key.toString();
    }

    private String getCombineKey(JoinPoint joinPoint) {
        StringBuffer key = new StringBuffer();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        key.append(method.getDeclaringClass().getName())
                .append("-")
                .append(method.getName());
        return key.toString();
    }

    private String getKey(JoinPoint  point, LimitType limitType, String originKey, String prefix) throws UnknownHostException {
        String key = "";
        switch (limitType) {
            case IP:
                key = WebUtil.getIP();
                break;
            case USER:
                Long userId = SecurityUtil.getUserId();
                if(userId == null) {
                    ExceptionUtil.rethrowCustomException("获取不到用户信息");
                }
                key = String.valueOf(userId);
                break;
            case METHOD:
//                key = ((Class<?>) point.getTarget()).getName() + ":" + ((MethodSignature) point.getSignature()).getMethod().getName();
                key = getCombineKey(point);
                break;
            case CUSTOM:
                key = String.valueOf(resolve(point, originKey));
                break;
            default:
                key = "";
        }
        if (key.isEmpty()) {
            throw new RuntimeException("Key不能为空");
        }
        return prefix + key;
    }

    public Object resolve(JoinPoint joinPoint, String placeholder) {

        if (placeholder.isEmpty()) {
            return null;
        }

        Object value = null;
        if (placeholder.matches("#\\{\\D*\\}")) {// 匹配上#{},则把内容当作变量
            String param = placeholder.replaceAll("#\\{", "").replaceAll("\\}", "");
            if (param.contains(".")) { // 多层引用
                try {
                    value = complexResolve(joinPoint, param);
                } catch (Exception e) {
                    logger.error("fail to resolve value for {}", param, e);
                }
            } else {
                value = simpleResolve(joinPoint, param);
            }
        } else {
            value = placeholder;
        }
        return value;
    }

    /**
     * 多层引用参数解析值
     *
     * @param joinPoint
     * @param placeholder
     * @return
     * @throws Exception
     */
    private Object complexResolve(JoinPoint joinPoint, String placeholder) throws Exception {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String[] names = methodSignature.getParameterNames();
        Object[] args = joinPoint.getArgs();
        String[] params = placeholder.split("\\.");
        System.out.println("args..."+ Arrays.toString(args));
        System.out.println("names..."+ Arrays.toString(names));
        System.out.println("params..."+ Arrays.toString(params));
        for (int i = 0; i < names.length; i++) {
            if (params[0].equals(names[i])) {
                Object obj = args[i];
                if (obj instanceof Map) {
                    Map objMap = (Map) obj;
                    return objMap.get(params[1]);
                }
                Method getMethod = obj.getClass().getDeclaredMethod(getMethodName(params[1]), null);
                Object value = getMethod.invoke(args[i]);
                return getValue(value, 1, params);
            }
        }
        return null;
    }

    /**
     * 简单参数获取值
     *
     * @param joinPoint
     * @param placeholder
     * @return
     */
    private Object simpleResolve(JoinPoint joinPoint, String placeholder) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String[] names = methodSignature.getParameterNames();
        Object[] args = joinPoint.getArgs();
        System.out.println("args..."+ Arrays.toString(args));
        System.out.println("names..."+ Arrays.toString(names));
        for (int i = 0; i < names.length; i++) {
            if (placeholder.equals(names[i])) {
                return args[i];
            }
        }
        return null;
    }

    private Object getValue(Object obj, int index, String[] params) throws Exception {
        if (obj != null && index < params.length - 1) {
            Method method = obj.getClass().getDeclaredMethod(getMethodName(params[index + 1]), null);
            obj = method.invoke(obj);
            getValue(obj, index + 1, params);
        }
        return obj;
    }

    private String getMethodName(String name) {
        return "get" + StringUtils.capitalize(name);
    }

}
